//
//  MyQRView.swift
//  zhendeBusiness
//
//  Created by 陆文宇 on 2017/6/21.
//  Copyright © 2017年 chenliang. All rights reserved.
//

import UIKit
import Alamofire

class MyQRView: UIView {
    
    @IBOutlet weak var shopNameLabel: UILabel!
    @IBOutlet weak var codeImageView: UIImageView!
    @IBOutlet weak var logoImageView: UIImageView!
    @IBOutlet weak var saveBackView: UIView!

    static func newInstance() -> MyQRView? {
        let nibView = Bundle.main.loadNibNamed("MyQRView", owner: nil, options: nil)
        if let view = nibView?.first as? MyQRView {
            
            view.frame = UIScreen.main.bounds
            view.backgroundColor = UIColor.black.withAlphaComponent(0.75)
            view.logoImageView.layer.cornerRadius = 5
            view.logoImageView.layer.borderWidth = 2
            view.logoImageView.layer.borderColor = UIColor.white.cgColor
            view.requestName()
            view.codeImageView.image = view.creatQRCodeOfMine(codeUrl: "/pay/byQr?id=" + RealmOperate.getConfig(key: appConfig_shop_id)!, width: 200, height: 200, baseColor: UIColor.white, codeColor: UIColor.black)
            let saveTap = UITapGestureRecognizer(target: view, action: #selector(save))
            view.saveBackView.addGestureRecognizer(saveTap)
            
            let dismissTap = UITapGestureRecognizer(target: view, action: #selector(dismiss))
            view.addGestureRecognizer(dismissTap)
            
            return view
        }
        return nil
    }
    
    func requestName() {
        let token = RealmOperate.getConfig(key: appConfig_user_token)!
        let params = ["token": token]
        
        _ = ZDAlamofire.get(url: "\(apiUrlPrex)/s/shop/detail", parameters: params, completionHandler: { (success, data) in
            if success {
                let shop = data as! [String:Any]
                if let shopName = shop["shopName"] as? String {
                    self.shopNameLabel.text = shopName
                }
            } else {
                Log(data ?? "no error")
                THToast.show("请检查网络状况")
            }
        })
    }
    
    func save() {
        YYPhotoHandler.available(authorized: {
            UIGraphicsBeginImageContextWithOptions(CGSize(width: 200, height: 200), false, 0);
            self.codeImageView.image?.draw(in: CGRect(x: 0, y: 0, width: 200, height: 200))
            UIImage(named: "qr_logo")?.draw(in: CGRect(x: 85, y: 85, width: 30, height: 30))
            if let image = UIGraphicsGetImageFromCurrentImageContext() {
                YYPhotoHandler.addImagesIntoUserLibrary(images: [image]) { (_, success, error) in
                    if success {
                        THToast.show("保存成功")
                    } else {
                        THToast.show("保存失败")
                        Log(error ?? "no errmsg")
                    }
                }
            } else {
                THToast.show("图片生成失败，请再试一遍")
            }
            UIGraphicsEndImageContext()
        }, denied: {
            THToast.show("未能获取相册权限")
        })
    }
    
    func dismiss() {
        removeFromSuperview()
    }
    
    func creatQRCodeOfMine(codeUrl : String, width : CGFloat, height : CGFloat, baseColor : UIColor, codeColor : UIColor) -> UIImage {
        
        let data = codeUrl.data(using: String.Encoding.utf8)
        //系统自带的
        //        CIAztecCodeGenerator
        //        CICode128BarcodeGenerator
        //        CIPDF417BarcodeGenerator
        //        CIQRCodeGenerator
        //实例化二维码滤镜
        let filter = CIFilter(name: "CIQRCodeGenerator")
        //        //恢复滤镜的默认属性
        //        filter?.setDefaults()
        //通过KVO设置滤镜inputMessage数据
        filter?.setValue(data, forKey: "inputMessage")
        filter?.setValue("H", forKey: "inputCorrectionLevel")
        
        //上色（设置二维码的底色和码色，input0是码色，input1是底色）
        let colorFilter = CIFilter(name: "CIFalseColor", withInputParameters: ["inputImage":filter!.outputImage!,"inputColor0":CIColor(cgColor: codeColor.cgColor),"inputColor1":CIColor(cgColor: baseColor.cgColor)])
        
        
        //获得滤镜输出的图像
        let qrCodeImage = colorFilter!.outputImage
        let scaleX = width / (qrCodeImage?.extent.size.width)!
        let scaleY = height / (qrCodeImage?.extent.size.height)!
        let transformedImage = qrCodeImage?.applying(CGAffineTransform.identity.scaledBy(x: scaleX, y: scaleY))
        return UIImage.init(ciImage: transformedImage!)
    }

    /*
    // Only override draw() if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func draw(_ rect: CGRect) {
        // Drawing code
    }
    */

}
